import { useEffect, useState } from 'react';
import ReactDOM from 'react-dom/client'
import 'reset-css'
import 'antd/dist/antd.css';
import '@/assets/style/global.scss'
import App from './App'
import { BrowserRouter } from "react-router-dom"
import 'moment/dist/locale/zh-cn'
import locale from 'antd/es/locale/zh_CN';
import { ConfigProvider } from 'antd';
// 状态管理
import { Provider } from 'react-redux'
import store from '@/store'


const Main = () => {
  const setUsedMenu = store((state) => state.setUsedMenu);
  const [createDom, seCreateDom] = useState<any>(false)

  useEffect(() => {
    //如果不是从中台过来的，就到我们自己的登录页
    const query = new URLSearchParams(window.location.search);
    const code = query.get('code');
    if (!code) {
      // 本地调试存本地, 修改token和cloudjsToken
      // localStorage.setItem("usedMenu", JSON.stringify(["/workplace", "/dashBoard"]))
      // setUsedMenu('["/workplace","/dashBoard"]')
      // localStorage.setItem("userInfo", JSON.stringify({ "sex": null, "userId": "1716382188871753728", "postId": null, "userName": "超级管理员", "memberId": null, "memberName": null, "tenantId": "1716382188871749632", "tenantName": null, "siteId": null, "siteName": null, "staffId": null, "deptId": null, "telephone": "19983510645", "userType": null, "platformTypeEnum": "TENANT", "loginTime": null, "merchantId": null, "merchantName": null, "storeId": null, "storeName": null, "businessTypeEnumType": null, "channelId": null, "businessId": null, "isAdmin": 1, "avatar": null, "appId": null, "uuid": null, "appIds": null }))
      // localStorage.setItem("token", 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxOTk4MzUxMDY0NSIsImp0aSI6IjJtMTlBWTVHNzNJM0xEWm5hOVJzQ0VXQUtwYyIsImNsaWVudF9pZCI6ImNiOGYxNDE2M2QxYzExZWM5NmU4MDBlMDRjMzEwMjUzIiwic2NvcGUiOlsiZ2V0X3VzZXJfaW5mbyJdfQ.JiiIZj5yJYbxjkGPrwjhmAJPUn4rpcUvBCT4FWPs0WChaiU5bb6_If_PdvLgaBOyY2WntH00i7iKhu8kjku_WqZMcNHGpaPfPwOlT4daO13NZId4u16oqZmmT_XZfGRzPVb5Ri-aUlkgmYEOwx8GZyT9U7hCz5E65mBGxIUMn531oTBORTE7fQUgXbJ9MGagGKOYl4r87FnShg4NjhANY1sz75_H5joXW-v2apnGFhUPfc6u13P-B6QRDP7uN2iVnAriLldvd-obhHb4_KyHOx6qYtP8sIWf_ownoCedUtAdHOFsWO4rljjErYaheFy5HERrMgSd-dhfZj15kB_gHA')
      // localStorage.setItem("cloudjsToken", 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiIxOTk4MzUxMDY0NSIsImp0aSI6IjJtMTlBWTVHNzNJM0xEWm5hOVJzQ0VXQUtwYyIsImNsaWVudF9pZCI6ImNiOGYxNDE2M2QxYzExZWM5NmU4MDBlMDRjMzEwMjUzIiwic2NvcGUiOlsiZ2V0X3VzZXJfaW5mbyJdfQ.JiiIZj5yJYbxjkGPrwjhmAJPUn4rpcUvBCT4FWPs0WChaiU5bb6_If_PdvLgaBOyY2WntH00i7iKhu8kjku_WqZMcNHGpaPfPwOlT4daO13NZId4u16oqZmmT_XZfGRzPVb5Ri-aUlkgmYEOwx8GZyT9U7hCz5E65mBGxIUMn531oTBORTE7fQUgXbJ9MGagGKOYl4r87FnShg4NjhANY1sz75_H5joXW-v2apnGFhUPfc6u13P-B6QRDP7uN2iVnAriLldvd-obhHb4_KyHOx6qYtP8sIWf_ownoCedUtAdHOFsWO4rljjErYaheFy5HERrMgSd-dhfZj15kB_gHA')

      seCreateDom(true)
      return
    }
    const script = document.createElement('script');
    script.type = 'text/javascript';
    var env = import.meta.env.VITE_APP_ENV
    if (env === 'test' || env === 'dev') {
      script.src = `https://admin-uat.028wlkj.com:1020/WL_Http_Cloud.js?v=${Date.now()}`;
    } else {
      script.src = `https://admin.028wlkj.com:1020/WL_Http_Cloud.js?v=${Date.now()}`;
    }
    document.getElementsByTagName('head')[0].appendChild(script);
    script.onload = (e) => {
      const _WLCloudJs = new WLCloudJs()
      _WLCloudJs.getData((result) => {
        if (result.code === "200") {
          localStorage.setItem("menus", JSON.stringify(result.data)) //将菜单存本地
          const menus = JSON.parse(localStorage.getItem("menus"))
          if (menus != null) {
            //登录后的权限数组,得到只有path的路由数组
            var usedMenu = []
            menus?.resourceTreeList.forEach(function (el) {
              if (el.childResource < 1) {
                usedMenu.push(el.resourceUrl)  //1级
              } else {
                el.childResource.forEach(function (e) {
                  usedMenu.push(e.resourceUrl)  //2级
                  if (e.childResource) {
                    e.childResource.forEach(function (item) {
                      usedMenu.push(item.resourceUrl)  //3级
                    })
                  }
                })
              }
            })
            localStorage.setItem("usedMenu", JSON.stringify(usedMenu))
            setUsedMenu(JSON.stringify(usedMenu))
          }
          _WLCloudJs.getUserInfo((result) => {
            if (result.code === '200') {
              localStorage.setItem("userInfo", JSON.stringify(result.data)) //将用户信息存本地
              //获取到了菜单和用户信息才创建DOM
              seCreateDom(true)
            }
            if (result.code !== '200') {
              if (env === 'test' || env === 'dev') {
                window.location.href = 'https://admin-uat.028wlkj.com:1020/login';
              } else {
                window.location.href = 'https://admin.028wlkj.com:1020/login';
              }
            }
          })
        }
        if (result.code !== "200") {
          if (env === 'test' || env === 'dev') {
            window.location.href = 'https://admin-uat.028wlkj.com:1020/login';
          } else {
            window.location.href = 'https://admin.028wlkj.com:1020/login';
          }
        }
      })
    }


  }, [])

  return (
    <div>
      {createDom && <ConfigProvider locale={locale} componentSize="middle">
        <Provider store={store}>
          {/* <React.StrictMode> */}
          <BrowserRouter>
            <App />
          </BrowserRouter>
          {/* </React.StrictMode> */}
        </Provider>
      </ConfigProvider>}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(<Main />);

